from rest_framework import serializers
from django.contrib.auth import get_user_model
from .models import *
import uuid
from django.conf import settings
User = get_user_model()

class UserSerializer(serializers.ModelSerializer):
    avatar = serializers.SerializerMethodField()
    
    class Meta:
        model = User
        fields = ('id', 'username', 'avatar', 'email', 'phone', 'uid', 'is_superuser')
        read_only_fields = ('id',)

    def get_avatar(self, obj):
        """获取用户头像，如果为空则返回默认头像"""
        if obj.avatar and obj.avatar.name:
            # 构建完整的URL路径
            request = self.context.get('request')
            if request:
                return request.build_absolute_uri(obj.avatar.url)
            else:
                return f"{settings.MEDIA_URL}{obj.avatar.name}"
        return 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'


class UserCreateSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True)
    
    class Meta:
        model = User
        fields = ('username', 'password', 'email', 'phone')
        
    def validate_username(self, value):
        """校验用户名是否已存在"""
        if User.objects.filter(username=value).exists():
            raise serializers.ValidationError("用户名已存在，请选择其他用户名")
        return value
    
    def validate_email(self, value):
        """校验邮箱是否已存在（如果提供了邮箱）"""
        if value and User.objects.filter(email=value).exists():
            raise serializers.ValidationError("邮箱已被使用，请选择其他邮箱")
        return value
    
    def validate_phone(self, value):
        """校验手机号是否已存在（如果提供了手机号）"""
        if value and User.objects.filter(phone=value).exists():
            raise serializers.ValidationError("手机号已被使用，请选择其他手机号")
        return value
    
    def generate_unique_uid(self):
        """生成唯一的UID"""
        while True:
            # 生成一个基于UUID4的短UID
            uid = str(uuid.uuid4()).replace('-', '')[:12].upper()
            # 检查是否已存在
            if not User.objects.filter(uid=uid).exists():
                return uid
        
    def create(self, validated_data):    
        # 自动生成唯一的UID
        uid = self.generate_unique_uid()
                
        user = User.objects.create_user(
            username=validated_data['username'],
            password=validated_data['password'],
            email=validated_data.get('email', ''),
            phone=validated_data.get('phone', None),
            uid=uid,
        )
        return user


class UserUpdateSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True, required=False)
    newPassword = serializers.CharField(write_only=True, required=False)
    
    class Meta:
        model = User
        fields = ('username', 'email', 'phone', 'uid', 'password', 'newPassword')
    
    def validate_username(self, value):
        """校验用户名是否已存在（排除当前用户）"""
        if self.instance and User.objects.filter(username=value).exclude(id=self.instance.id).exists():
            raise serializers.ValidationError("用户名已存在，请选择其他用户名")
        return value
    
    def validate_email(self, value):
        """校验邮箱是否已存在（排除当前用户，如果提供了邮箱）"""
        if value and self.instance and User.objects.filter(email=value).exclude(id=self.instance.id).exists():
            raise serializers.ValidationError("邮箱已被使用，请选择其他邮箱")
        return value
    
    def validate_phone(self, value):
        """校验手机号是否已存在（排除当前用户，如果提供了手机号）"""
        if value and self.instance and User.objects.filter(phone=value).exclude(id=self.instance.id).exists():
            raise serializers.ValidationError("手机号已被使用，请选择其他手机号")
        return value
    
    def validate_uid(self, value):
        """校验UID是否已存在（排除当前用户，如果提供了UID）"""
        if value and self.instance and User.objects.filter(uid=value).exclude(id=self.instance.id).exists():
            raise serializers.ValidationError("UID已存在，请选择其他UID")
        return value
        
    def update(self, instance, validated_data):
        # 处理密码更新
        password = validated_data.pop('password', None)
        new_password = validated_data.pop('newPassword', None)
        
        # 如果有新密码，使用新密码；否则使用password字段
        if new_password:
            instance.set_password(new_password)
        elif password:
            instance.set_password(password)
        
        # 确保phone字段为None而不是空字符串
        if 'phone' in validated_data and not validated_data['phone']:
            validated_data['phone'] = None
                
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        instance.save()
        return instance


class TodoListSerializer(serializers.ModelSerializer):
    created_by = serializers.SerializerMethodField()
    
    class Meta:
        model = TodoList
        fields = ['id', 'description', 'created_by']

    def get_created_by(self, obj):
        if obj.created_by:
            return obj.created_by.username
        return None


class AvatarUploadSerializer(serializers.Serializer):
    """头像上传序列化器"""
    avatar = serializers.ImageField()
    
    def validate_avatar(self, value):
        """校验头像文件"""
        import os
        
        # 验证文件类型
        allowed_extensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp']
        file_extension = os.path.splitext(value.name)[1].lower()
        if file_extension not in allowed_extensions:
            raise serializers.ValidationError('不支持的文件格式，请上传 JPG、PNG、GIF 或 BMP 格式的图片')
        
        # 验证文件大小 (限制为5MB)
        if value.size > 5 * 1024 * 1024:
            raise serializers.ValidationError('文件大小不能超过5MB')
        
        return value
